<?php

declare(strict_types=1);

namespace app\shop\controller\api\app;

use think\Request;
use app\shop\controller\api\ShopBase;
use app\shop\model\app\mplive\Room;
use app\shop\facade\Wechat;

class Mplive extends ShopBase
{
    protected $wechat;

    public function getRoomList(Request $request)
    {

        // 通过客户端访问触发，每10分钟刷新一次房间状态
        $lastUpdateTime = cache('wechatMplive.update');
        if ($lastUpdateTime < (time() - 60 * 10)) {
            cache('wechatMplive.update', time());
            $service = new \app\shop\service\third\wechat\MiniProgram();
            $res = $service->wechat->broadcast->getRooms();
            $data = [];
            if (isset($res['errcode']) && ($res['errcode'] !== 0 && $res['errcode'] !== 1001)) {
                return error($res['errmsg'] ?? '');
            } else {
                Room::where(true)->delete();
                foreach ($res['room_info'] as $room) {
                    $room['status'] = $room['live_status'];
                    $room['type'] = $room['live_type'];
                    $data[] = $room;
                }
                Room::strict(false)->insertAll($data);
            }
        }

        $params = $this->request->param();

        $ids = $params['ids'] ?? '';

        $list = Room::where('roomid', 'in', $ids)->select();

        return success('获取成功', $list);
    }

    public function getMpLink()
    {
        $wechat = Wechat::miniProgram();
        // TODO: 需防止被恶意消耗次数
        $res = $wechat->url_scheme->generate();
        $link = $res['openlink'];
        return success('获取成功', $link);
    }
}
